<!--
 * 侧边栏容器组件
 * 功能：包含搜索来源链接卡片和相关推荐的侧边栏区域
 * 作者：MetasoCreator Team
 * 创建时间：2025-01-19
 * 修改时间：2025-01-19
-->

<template>
  <div class="sidebar-container" :class="{ 'collapsed': collapsed }">
    <!-- 侧边栏头部 -->
    <div class="sidebar-header">
      <div class="header-content">
        <el-icon class="header-icon"><Link /></el-icon>
        <span v-if="!collapsed" class="header-title">搜索来源</span>
      </div>
      <el-button
        size="small"
        text
        @click="toggleCollapse"
        class="collapse-button"
        :title="collapsed ? '展开侧边栏' : '收起侧边栏'"
      >
        <el-icon>
          <ArrowLeft v-if="!collapsed" />
          <ArrowRight v-else />
        </el-icon>
      </el-button>
    </div>

    <!-- 侧边栏内容 -->
    <div v-if="!collapsed" class="sidebar-content">
      <!-- 搜索来源卡片 -->
      <div v-if="sources.length > 0" class="sources-section">
        <div class="section-title">
          <el-icon><Document /></el-icon>
          <span>相关链接 ({{ sources.length }})</span>
        </div>
        <div class="sources-list">
          <SourceCard
            v-for="(source, index) in displaySources"
            :key="source.id || index"
            :source="source"
            @click="handleSourceClick"
            @read="handleReadSource"
          />
        </div>
      </div>

      <!-- 数据来源卡片面板 -->
      <div v-if="displaySources.length > 0" class="link-cards-section">
        <div class="section-title">
          <el-icon><Link /></el-icon>
          <span>数据来源 ({{ displaySources.length }})</span>
        </div>
        <div class="cards-list">
          <div 
            v-for="card in displaySources" 
            :key="card.id"
            class="link-card"
            @click="openLink(card.url)"
          >
            <div class="card-header">
              <h4 class="card-title">{{ card.title }}</h4>
              <span v-if="card.score" class="card-score">{{ card.score }}%</span>
            </div>
            <p class="card-description">{{ card.description }}</p>
            <div class="card-footer">
              <span class="card-url">{{ card.source || card.domain || getDomainFromUrl(card.url) }}</span>
              <div class="card-tags" v-if="card.tags">
                <span 
                  v-for="tag in card.tags" 
                  :key="tag"
                  class="tag"
                >
                  {{ tag }}
                </span>
              </div>
              <div class="card-tags" v-else-if="card.contentType">
                <span class="tag">{{ card.contentType }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="displaySources.length === 0" class="empty-state">
        <el-empty
          :image-size="80"
          description="暂无相关链接"
        >
          <template #image>
            <el-icon size="80" color="var(--text-placeholder)">
              <Document />
            </el-icon>
          </template>
          <template #description>
            <span class="empty-description">
              开始搜索后，相关链接将显示在这里
            </span>
          </template>
        </el-empty>
      </div>

      <!-- 操作按钮 -->
      <div v-if="displaySources.length > 0" class="sidebar-actions">
        <el-button
          size="small"
          type="primary"
          text
          @click="exportSources"
          :disabled="displaySources.length === 0"
        >
          <el-icon><Download /></el-icon>
          <span>导出链接</span>
        </el-button>
        <el-button
          size="small"
          type="danger"
          text
          @click="clearSources"
          :disabled="displaySources.length === 0"
        >
          <el-icon><Delete /></el-icon>
          <span>清空</span>
        </el-button>
      </div>
    </div>

    <!-- 收起状态的快捷操作 -->
    <div v-else class="collapsed-content">
      <div class="collapsed-stats">
        <div class="stat-item" :title="`${sources.length} 个相关链接`">
          <el-badge :value="sources.length" :hidden="sources.length === 0">
            <el-icon><Document /></el-icon>
          </el-badge>
        </div>
        <div class="stat-item" :title="`${displaySources.length} 个数据来源`">
          <el-badge :value="displaySources.length" :hidden="displaySources.length === 0">
            <el-icon><Link /></el-icon>
          </el-badge>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Link,
  ArrowLeft,
  ArrowRight,
  Document,
  Star,
  Download,
  Delete
} from '@element-plus/icons-vue'
import SourceCard from './SourceCard.vue'


// Props
const props = defineProps({
  sources: {
    type: Array,
    default: () => []
  },
  collapsed: {
    type: Boolean,
    default: false
  },
  searchSources: {
    type: Array,
    default: () => []
  }
})

// 工具方法
const getDomainFromUrl = (url) => {
  if (!url) return '未知来源'
  try {
    const urlObj = new URL(url)
    return urlObj.hostname
  } catch {
    return '未知来源'
  }
}

// Emits
const emit = defineEmits([
  'source-click',
  'read-source',
  'export-sources',
  'clear-sources',
  'toggle-collapse'
])

// 响应式数据
const collapsed = ref(props.collapsed)

// 计算属性
const displaySources = computed(() => {
  return props.searchSources || []
})

// 方法
const toggleCollapse = () => {
  collapsed.value = !collapsed.value
  emit('toggle-collapse', collapsed.value)
}

const handleSourceClick = (source) => {
  emit('source-click', source)
}

const handleReadSource = (source) => {
  emit('read-source', source)
}

// 打开链接
const openLink = (url) => {
  window.open(url, '_blank')
}

const exportSources = () => {
  if (displaySources.value.length === 0) {
    ElMessage.warning('暂无链接可导出')
    return
  }
  
  try {
    // 生成导出内容
    const exportData = displaySources.value.map((source, index) => {
      return `${index + 1}. ${source.title}\n   ${source.url}\n   ${source.description || ''}\n`
    }).join('\n')
    
    const content = `MetasoCreator 数据来源导出\n生成时间: ${new Date().toLocaleString()}\n\n${exportData}`
    
    // 创建下载链接
    const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `数据来源_${new Date().toISOString().slice(0, 10)}.txt`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    
    ElMessage.success('链接导出成功')
    emit('export-sources', displaySources.value)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

const clearSources = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有数据来源吗？此操作不可撤销。',
      '确认清空',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    emit('clear-sources')
    ElMessage.success('已清空所有数据来源')
  } catch {
    // 用户取消操作
  }
}
</script>

<style scoped>
.sidebar-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: var(--bg-secondary);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: all 0.3s ease;
  min-width: 300px;
}

.sidebar-container.collapsed {
  min-width: 60px;
  max-width: 60px;
}

.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid var(--border-color);
  background: var(--bg-primary);
}

.header-content {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--text-primary);
}

.header-icon {
  font-size: 18px;
  color: var(--color-primary);
}

.header-title {
  font-size: 16px;
  font-weight: 600;
}

.collapse-button {
  padding: 4px;
  border-radius: 4px;
}

.sidebar-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.sources-section,
.link-cards-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 16px 16px 12px 16px;
  font-size: 14px;
  font-weight: 600;
  color: var(--text-secondary);
  border-bottom: 1px solid var(--border-color-light);
}

.sources-list,
.cards-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
}

.empty-description {
  color: var(--text-placeholder);
  font-size: 14px;
  text-align: center;
  line-height: 1.5;
}

.sidebar-actions {
  display: flex;
  gap: 8px;
  padding: 12px 16px;
  border-top: 1px solid var(--border-color-light);
  background: var(--bg-primary);
}

.sidebar-actions .el-button {
  flex: 1;
}

/* 收起状态样式 */
.collapsed-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px 8px;
}

.collapsed-stats {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 8px;
  border-radius: 8px;
  background: var(--bg-primary);
  cursor: pointer;
  transition: all 0.2s ease;
}

.stat-item:hover {
  background: var(--color-primary-light);
  transform: scale(1.05);
}

.stat-item .el-icon {
  font-size: 20px;
  color: var(--color-primary);
}

/* 链接卡片样式 */
.link-card {
  background: var(--bg-primary);
  border: 1px solid var(--border-color-light);
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.link-card:hover {
  border-color: var(--color-primary);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-1px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.card-title {
  font-size: 14px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
  line-height: 1.4;
  flex: 1;
}

.card-score {
  font-size: 12px;
  color: var(--color-success);
  font-weight: 600;
  background: var(--color-success-light);
  padding: 2px 6px;
  border-radius: 4px;
  margin-left: 8px;
}

.card-description {
  font-size: 12px;
  color: var(--text-secondary);
  line-height: 1.4;
  margin: 0 0 8px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 8px;
}

.card-url {
  font-size: 11px;
  color: var(--text-placeholder);
  flex-shrink: 0;
}

.card-tags {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.tag {
  font-size: 10px;
  color: var(--color-primary);
  background: var(--color-primary-light);
  padding: 1px 4px;
  border-radius: 3px;
  white-space: nowrap;
}

/* 滚动条样式 */
.sources-list::-webkit-scrollbar,
.cards-list::-webkit-scrollbar {
  width: 4px;
}

.sources-list::-webkit-scrollbar-track,
.cards-list::-webkit-scrollbar-track {
  background: transparent;
}

.sources-list::-webkit-scrollbar-thumb,
.cards-list::-webkit-scrollbar-thumb {
  background: var(--border-color);
  border-radius: 2px;
}

.sources-list::-webkit-scrollbar-thumb:hover,
.cards-list::-webkit-scrollbar-thumb:hover {
  background: var(--text-secondary);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .sidebar-container {
    min-width: 280px;
  }
}

@media (max-width: 768px) {
  .sidebar-container {
    min-width: 100%;
    border-radius: 0;
  }
  
  .sidebar-container.collapsed {
    min-width: 50px;
    max-width: 50px;
  }
  
  .sidebar-header {
    padding: 12px;
  }
  
  .sidebar-actions {
    flex-direction: column;
  }
}

/* 暗色主题适配 */
:root[data-theme="dark"] .sidebar-container {
  background: var(--bg-secondary);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

:root[data-theme="dark"] .sidebar-header {
  background: var(--bg-primary);
  border-bottom-color: var(--border-color);
}

:root[data-theme="dark"] .sidebar-actions {
  background: var(--bg-primary);
  border-top-color: var(--border-color);
}

:root[data-theme="dark"] .stat-item {
  background: var(--bg-primary);
}

:root[data-theme="dark"] .stat-item:hover {
  background: var(--color-primary-dark);
}

/* 动画效果 */
.sidebar-container {
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateX(20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 徽章样式调整 */
.stat-item :deep(.el-badge__content) {
  font-size: 10px;
  min-width: 16px;
  height: 16px;
  line-height: 16px;
}
</style>